package com.qianjiangcloud.store.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.activity.account.AccountLoginFragment;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.util.loader.FileUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.FileSystem.FileSystem;


/**
 * Created by Jelly on 2016/8/2.
 */
public class ApplyforChargeBackFragment extends BaseDoFragment implements View.OnClickListener{
    private RelativeLayout mReason;
    private EditText mExplain;
    private ImageView mSelectImage;
    private Dialog mDialog;
    private TextView mShowText;
    private ListView mReasonList;
    private String orderId;
    private JSONArray mItemsList;
    private List<String> mList = new ArrayList<String>();
    private List<String> reasonList=new ArrayList<String>();
    private ArrayAdapter<String> arrayAdapter;
    private RecyclerView mRecyclerView;
    private MyReasonAdapter myReasonAdapter;


    private static final int TAKE_PHOTO_ID = Menu.FIRST;
    private static final int SELECT_PHOTO_ID = Menu.FIRST + 1;
    public int i=0;
    private ArrayList<String> imagePath=new ArrayList<String>();
    private MyAdapter myAdapter;
    private LayoutInflater mInflate;
    private File mFile;
    private String afertReason="";
    private String afterExplain="";
    private JSONArray all;
    private Dialog dialog;
    public PopupWindow popupWindow;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setTitle(mActivity.getString(R.string.perfect_application));
        mActionBar.setRightTitleButton(mActivity.getString(R.string.account_signature_submit), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (afertReason.equals("")){
                    Toast.makeText(mActivity,"请选择退货原因",Toast.LENGTH_LONG).show();
                    return;
                }
                afterExplain=mExplain.getText().toString();
                Run.excuteJsonTask(new JsonTask(),new SaveRequest());

            }
        });
        Intent intent=mActivity.getIntent();
        String json=intent.getStringExtra("json");
        orderId=intent.getStringExtra("orderId");
        String reason=intent.getStringExtra("reason");
            try {
                if (json!=null) {
                    all = new JSONArray(json);
                    if (all != null && all.length() > 0) {
                        for (int i = 0; i < all.length(); i++) {
                            mList.add(all.getString(i));
                        }
                    }
                }
                if (reason!=null) {
                    mItemsList = new JSONArray(reason);
                    if (mItemsList!=null&&mItemsList.length()>0){
                        for (int i=0;i<mItemsList.length();i++) {
                            reasonList.add(mItemsList.getString(i));
                        }
                    }

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        mInflate=inflater;
        rootView = inflater.inflate(R.layout.fragmet_chargeback, null);
        mReason= (RelativeLayout) findViewById(R.id.relative_reason);
        mShowText= (TextView) findViewById(R.id.tv_show);
        mShowText.setText("请选择");
        mExplain= (EditText) findViewById(R.id.after_explain);
        mSelectImage= (ImageView) findViewById(R.id.add_evidence);
        mRecyclerView= (RecyclerView) findViewById(R.id.recycle);
        mReason.setOnClickListener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        myAdapter=new MyAdapter();
        mRecyclerView.setAdapter(myAdapter);
        arrayAdapter=new ArrayAdapter<String>(mActivity,android.R.layout.simple_spinner_item,reasonList);
        arrayAdapter.setDropDownViewResource(R.layout.fragment_spinner_item);
        mSelectImage.setOnClickListener(this);
        mDialog = new Dialog(mActivity, R.style.select_popum_dialog);
        View diaViw = inflater.inflate(R.layout.select_pic_popup, null);
        mDialog.setContentView(diaViw);
        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setAttributes(lp);
        diaViw.findViewById(R.id.btn_pick_photo).setOnClickListener(this);
        diaViw.findViewById(R.id.btn_take_photo).setOnClickListener(this);
        diaViw.findViewById(R.id.btn_cancel).setOnClickListener(this);
    }
    public void showPopuWindows(){
        View view=mInflate.inflate(R.layout.fragment_after_popuwind,null);
        mReasonList= (ListView) view.findViewById(R.id.show_reason_list);
        mReasonList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                afertReason=reasonList.get(i);
                mShowText.setText(afertReason);
                popupWindow.dismiss();
            }
        });
        myReasonAdapter=new MyReasonAdapter();
        mReasonList.setAdapter(myReasonAdapter);
        popupWindow=new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        popupWindow.showAsDropDown(mReason, Gravity.LEFT, 0);

    }

    //退货理由适配器
    public class MyReasonAdapter extends BaseAdapter{


        @Override
        public int getCount() {
            return reasonList.size();
        }

        @Override
        public Object getItem(int i) {
            return reasonList.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder holder=null;
            if (convertView==null){
                convertView=mInflate.inflate(R.layout.fragment_spinner_item,null);
                holder=new ViewHolder();
                holder.textView= (TextView) convertView.findViewById(R.id.show_reason);
                convertView.setTag(holder);
            } else {
                holder= (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(reasonList.get(i));
            return convertView;
        }
        public  class ViewHolder{
            public TextView textView;
        }
    }

    //凭证
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflate.inflate(R.layout.fragment_apply_evidence, null);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.iv_evidence1.setImageBitmap(getLoacalBitmap(imagePath.get(position)));

        }

        @Override
        public int getItemCount() {
            return imagePath.size();
        }


    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView iv_evidence1;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv_evidence1 = (ImageView) itemView.findViewById(R.id.evidence1);

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_evidence:
                mDialog.show();
                break;
            case R.id.btn_pick_photo:
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, SELECT_PHOTO_ID);
                mDialog.dismiss();
                break;
            case R.id.btn_take_photo:
                takePicture();
                mDialog.dismiss();
                break;
            case R.id.btn_cancel:
                mDialog.dismiss();
                break;
            case R.id.relative_reason:
                showPopuWindows();
                break;
            default:
                break;
        }
    }
    //打开相机
    public void takePicture() {
        try {
            mFile = FileUtils.createFile();
            Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
            startActivityForResult(i, TAKE_PHOTO_ID);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==SELECT_PHOTO_ID&&resultCode == Activity.RESULT_OK){
            if (i<3){
            i++;
            Uri uri = data.getData();
                try {

                    String path=getThumbUploadPath(getRealFilePath(mActivity,uri),1200);
                    imagePath.add(path);
                    myAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(mActivity,"最多只能上传3张图片",Toast.LENGTH_LONG).show();
                return;
            }
        } else if (TAKE_PHOTO_ID == requestCode && resultCode == Activity.RESULT_OK){
            if (i<3){
                i++;

                try {
                    String path=getThumbUploadPath(mFile.getAbsolutePath(),1200);
                    imagePath.add(path);
                    myAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(mActivity,"最多只能上传3张图片",Toast.LENGTH_LONG).show();
                return;
            }
        }
    }
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //uri转成路径
    public  String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    //对图片进行压缩
    private String getThumbUploadPath(String oldPath,int bitmapMaxWidth) throws Exception {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(oldPath, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int reqHeight = 0;
        int reqWidth = bitmapMaxWidth;
        reqHeight = (reqWidth * height)/width;
        // 在内存中创建bitmap对象，这个对象按照缩放大小创建的
        options.inSampleSize = calculateInSampleSize(options, bitmapMaxWidth, reqHeight);
//                System.out.println("calculateInSampleSize(options, 480, 800);==="
//                                + calculateInSampleSize(options, 480, 800));
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
        //Log.e("asdasdas", "reqWidth->"+reqWidth+"---reqHeight->"+reqHeight);
        Bitmap bbb = compressImage(Bitmap.createScaledBitmap(bitmap, bitmapMaxWidth, reqHeight, false));
        return saveImg(bbb, "evidence"+i);
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 2048) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            options -= 10;// 每次都减少10
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public  String saveImg(Bitmap b,String name) throws Exception{

      /*  File zip = new File(String.valueOf(FileSystem.getCachesDir(mActivity, true)));
        File f = new File(zip.getAbsolutePath(),name+".png");*/
        File f = new File(String.valueOf(FileSystem.getCachesDir(mActivity, true)),name);

        try {
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        b.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return f.getPath();
    }

    private class SaveRequest implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog_mt();
            try {
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    dialog= AccountLoginFragment.showAlertDialog(mActivity, all.optString("data"), null,
                            "确认", null, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
//                                    startActivity(AgentActivity.intentForFragment(mActivity,AgentActivity.FRAGMENT_AFTER_SALES)
//                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
//
//
                                    Intent it =new Intent(getActivity(),AccountAfterSalesActivity.class);
                                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                                    startActivity(it);

                                    dialog.dismiss();

                                }
                            }, false, null);

                } else {
                    dialog= AccountLoginFragment.showAlertDialog(mActivity, all.optString("data"), null,
                            "确认", null, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog.dismiss();
                                }
                            }, false, null);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public JsonRequestBean task_request() {
            showCancelableLoadingDialog();
            JsonRequestBean req = new JsonRequestBean(
                    "mobileapi.aftersales.return_save");
            String order_id = "";
            try {
                order_id = all.getJSONObject(0).optString("order_id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            req.addParams("order_id", order_id); // 订单号 String
            for (int i = 0; i < all.length(); i++) {
                JSONObject obj = all.optJSONObject(i);
                String product_id = obj.optJSONObject("products").optString(
                        "product_id");
                req.addParams("product_bn[" + product_id + "]",
                        obj.optString("bn")); // 货品号 Aarry
                req.addParams("product_nums[" + product_id + "]",
                        obj.optString("quantity")); // 发货数量
                // Aarry
                req.addParams("product_name[" + product_id + "]",
                        obj.optString("name")); // 货品名称 Aarry
                req.addParams("product_price[" + product_id + "]",
                        obj.optString("price")); // 货品价格
            }

            if (imagePath!=null&&imagePath.size()>0) {
                File[] files = new File[imagePath.size()];
                for (int i = 0; i < imagePath.size(); i++) {
                    files[i] = new File(imagePath.get(i));
                }
                req.files = files;
            }

            req.addParams("agree", "true"); // (是否同意售后服务 agree=on) boolean
            req.addParams("content",afterExplain);
            req.addParams("title",afertReason);
            req.addParams("type","1");

            return req;
        }

    }

}


